<?php
class Custom_Controller_Plugin_ModuleBasedLayout 
	extends Zend_Layout_Controller_Plugin_Layout
{
	public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
		//$this->getLayout()->setLayoutPath( 
		//	Zend_Registry::get('config')->resources->frontController->moduleDirectory
		//	. DS . $request->getModuleName() . DS . 'layouts' );
		
		// Changes the Layout based on the module name
        $front = Zend_Controller_Front::getInstance();
        $defaultModule = $front->getDefaultModule();
        $defaultLayoutPath = APPLICATION_PATH . "/modules/". $defaultModule ."/views";

        $modulename = $request->getModuleName();
        $layoutPath = APPLICATION_PATH . "/modules/". $modulename ."/views";
        $layout = Zend_Layout::getMvcInstance();
        if (is_dir($layoutPath) && is_readable($layoutPath)) {
            $layout->setLayoutPath($layoutPath)->setLayout($modulename);
            return;
        }
        if ($defaultModule != $modulename) { 
            return; 
        }
        if (is_dir($defaultLayoutPath)) {
            $layout->setLayoutPath($defaultLayoutPath)->setLayout($defaultModule);
        }
        return;
    }
} 